<template>
  <div class="p-2 container">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="抓拍时间">
              <el-date-picker v-model="startAndEnd" type="datetimerange" start-placeholder="开始日期" end-placeholder="结束日期" value-format="YYYY-MM-DD HH:mm:ss" @change="handleDateChange" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never" style="flex: 1; display: flex; flex-direction: column; position: relative">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button v-hasPermi="['camera:media_info:remove']" type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()" >
              删除
            </el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @query-table="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" :data="media_infoList" style="flex: 1;" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="抓拍图片" align="center">
          <template #default="scope">
            <ImagePreview :width="100" :height="100" :src="scope.row.filePath" :preview-src-list="[scope.row.filePath]" />
          </template>
        </el-table-column>
        <el-table-column label="抓拍位置" align="center" prop="parkBuildingName" />
        <el-table-column label="抓拍时间" align="center" prop="createTime" />
        <el-table-column label="操作人" align="center" prop="createName" />
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="下载" placement="top">
              <el-button v-hasPermi="['camera:media_info:edit']" link type="primary" @click="handleDownload(scope.row.fileId)">下载</el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button v-hasPermi="['camera:media_info:remove']" link type="primary" @click="handleDelete(scope.row)">删除</el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" :total="total" @pagination="getList" />
    </el-card>
    <!-- 添加或修改媒体库对话框 -->
    <el-drawer v-model="dialog.shouAdd" :title="dialog.title" width="500px" append-to-body>
      <el-form ref="media_infoFormRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="文件ID" prop="fileId">
          <el-input v-model="form.fileId" placeholder="请输入文件ID" />
        </el-form-item>
        <el-form-item label="抓拍设备ID" prop="equipmentId">
          <el-input v-model="form.equipmentId" placeholder="请输入抓拍设备ID" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-drawer>
    <el-dialog v-model="dialogPicView.shouAdd" :title="dialogPicView.title" width="500px" append-to-body>
      <el-image :src="picurl" lazy />
    </el-dialog>
  </div>
</template>

<script setup name="media_info" lang="ts">
import { addmedia_info, delmedia_info, listmedia_info, updatemedia_info } from '@/api/security/camera/media_info';
import { media_infoForm, media_infoQuery, media_infoVO } from '@/api/security/camera/media_info/types';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const media_infoList = ref<media_infoVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);

const queryFormRef = ref<ElFormInstance>();
const media_infoFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const dialogPicView = reactive<DialogOption>({
  visible: false,
  title: ''
});

const initFormData: media_infoForm = {
  mediaInfoId: undefined,
  fileId: undefined,
  equipmentId: undefined
};
const data = reactive<any>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    fileId: undefined,
    equipmentId: undefined,
    startTime: undefined,
    endTime: undefined,
    params: {}
  },
  rules: {
    mediaInfoId: [{ required: true, message: '主键ID不能为空', trigger: 'blur' }],
    fileId: [{ required: true, message: '文件ID不能为空', trigger: 'blur' }],
    equipmentId: [{ required: true, message: '抓拍设备ID不能为空', trigger: 'blur' }]
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询媒体库列表 */
const getList = async () => {
  loading.value = true;
  const res = await listmedia_info(queryParams.value);
  media_infoList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.shouAdd = false;
};

/** 表单重置 */
const reset = () => {
  form.value = { ...initFormData };
  media_infoFormRef.value?.resetFields();
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  startAndEnd.value = []
  queryParams.value.startTime = '';
  queryParams.value.endTime = '';
  handleQuery();
};

/** 多选框选中数据 */
const handleSelectionChange = (selection: media_infoVO[]) => {
  ids.value = selection.map((item) => item.mediaInfoId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};

/** 下载按钮操作 */
const handleDownload = (ossId: string) => {
  proxy?.$download.oss(ossId);
};

/** 修改按钮操作 */
let picurl = ref('');

/** 提交按钮 */
const submitForm = () => {
  media_infoFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.mediaInfoId) {
        await updatemedia_info(form.value).finally(() => (buttonLoading.value = false));
      } else {
        await addmedia_info(form.value).finally(() => (buttonLoading.value = false));
      }
      proxy?.$modal.msgSuccess('操作成功');
      dialog.shouAdd = false;
      await getList();
    }
  });
};

/** 删除按钮操作 */
const handleDelete = async (row?: media_infoVO) => {
  const _mediaInfoIds = row?.mediaInfoId || ids.value;
  await proxy?.$modal.confirm('确定删除该条数据？删除后数据不可恢复。').finally(() => (loading.value = false));
  await delmedia_info(_mediaInfoIds);
  proxy?.$modal.msgSuccess('删除成功');
  await getList();
};

/** 日期框改变 */
let startAndEnd = ref([]);
const handleDateChange = () => {
  if (startAndEnd.value != null) {
    if (startAndEnd.value[0] === startAndEnd.value[1]) {
      startAndEnd.value[1] = startAndEnd.value[1].substring(0, 10) + ' 23:59:59'
    }
    console.log(startAndEnd.value)
    queryParams.value.startTime = startAndEnd.value[0];
    queryParams.value.endTime = startAndEnd.value[1];
  } else {
    queryParams.value.startTime = '';
    queryParams.value.endTime = '';
  }
};

onMounted(() => {
  getList();
});
</script>
<style lang="scss" scoped>
:deep(.el-card__header) {
  height: 60px;
}

:deep(.el-card__body) {
  height: calc(100% - 60px);
  display: flex;
  flex-direction: column;
}

:deep(.pagination-container) {
  margin-top: 0;
}
</style>
